# -*- coding: utf-8 -*-
"""
Created on Sat Nov 14 15:07:48 2020

@author: 逍遥九少
"""

def SendCmdToStata(cmdtext):
    import win32gui, win32con
    win = win32gui.FindWindow(None, 'Stata/SE 11.2 - [Results]')
    tid_0 = win32gui.FindWindowEx(win, None, 'XTPDockingPaneTabbedContainer', 'Command')
    tid = win32gui.FindWindowEx(tid_0, None, 'RichEdit20A', None)
    win32gui.SendMessage(tid, win32con.WM_SETTEXT, None, cmdtext)
    win32gui.PostMessage(tid, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    win32gui.PostMessage(tid, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
#    print('已经成功发送并执行\t%s' %cmdtext)

#SendCmdToStata('caonima')

def ChooseLineToSend(filename, start_line, end_line):
    filepath = "D:/stata11/ado/personal/Course_A/" + filename
    with open(filepath, 'r', encoding = 'utf-8') as f:
        txt = f.read()
        f.close()
    lines = txt.split('\n')
    # 将输入的字符串转为数字
    start_line = int(start_line)
    end_line = int(end_line)
    start_line = start_line - 1 #python从0开始计数
    end_line = end_line #索引的时候左闭右开，所以不用管
    line_test = lines[start_line:end_line]
    import time
    for line in line_test:
        SendCmdToStata(line)
        time.sleep(0.01)
    messagebox.showinfo('Message', '已经执行完毕：从 第%s行 到 第%s行!' % (start_line+1,end_line))

#start_line = 26
#end_line = 37
#filename = 'D:/stata11/ado/personal/Course_A/A2_data.do'
#ChooseLineToSend(filename, start_line = start_line,end_line = end_line)


def SetTime(mydate = '2020/11/15', hour = 13, minites = 30):
    import os
    import datetime
    #设定日期
    _date = datetime.datetime.strptime(mydate,"%Y/%m/%d")
    #设定时间
    mytime = str(hour) + '.' + str(minites)
    _time = mytime
    #设定时间
    os.system('time {}'.format(_time))
    os.system('date {}'.format(_date))



def RecoverTime():
    import os
    import time
    import ntplib
    c = ntplib.NTPClient()
    response = c.request('cn.pool.ntp.org')
    ts = response.tx_time
    _date = time.strftime('%Y-%m-%d',time.localtime(ts)) 
    _time = time.strftime('%X',time.localtime(ts))
    os.system('date {} && time {}'.format(_date,_time))    


# 每次dt之前，就在现有的时间上加个5分
    
#myhour = 13
#myminites = 40
#SetTime(mydate = '2020/11/15', hour =myhour, minites = myminites)    


from tkinter import *
import tkinter.messagebox as messagebox

root= Tk()
root.title('Stata免复制粘贴外挂')
root.geometry('300x200') # 这里的乘号不是 * ，而是小写英文字母 x

do_path_label = Label(root, text = 'do文件名:')
do_path_label.grid(row=0, column=0)
do_path_label.place(relheight=0.1, relwidth=0.2, relx=0.2, rely=0.1)
do_path_entry = Entry(root)
do_path_entry.grid(row=0, column=1)
do_path_entry.place(relheight=0.1, relwidth=0.3, relx=0.5, rely=0.1)

start_line_label = Label(root, text = '起始行号:')
start_line_label.grid(row=1, column=0)
start_line_label.place(relheight=0.1, relwidth=0.2, relx=0.2, rely=0.3)
start_line_entry = Entry(root)
start_line_entry.grid(row=1, column=1)
start_line_entry.place(relheight=0.1, relwidth=0.2, relx=0.5, rely=0.3)

end_line_label = Label(root, text = '结束行号:')
end_line_label.grid(row=2, column=0)
end_line_label.place(relheight=0.1, relwidth=0.2, relx=0.2, rely=0.5)
end_line_entry = Entry(root)
end_line_entry.grid(row=2, column=1)
end_line_entry.place(relheight=0.1, relwidth=0.2, relx=0.5, rely=0.5)

run_button = Button(root, text='逐行复制粘贴运行', 
                    command=lambda:ChooseLineToSend(do_path_entry.get(), 
                                                    start_line_entry.get(), 
                                                    end_line_entry.get()))
run_button.grid(row=3, column=0, columnspan =2)
run_button.place(relheight=0.15, relwidth=0.4, relx=0.3, rely=0.7)

root.mainloop()


#class Application(Frame):
#    def __init__(self, master=None):
#        Frame.__init__(self, master)
#        self.pack()
#        self.createWidgets()
#
#    def createWidgets(self):
#        self.nameInput = Entry(self)
#        self.nameInput.pack()
#        self.alertButton = Button(self, text='Hello', command=self.hello)
#        self.alertButton.pack()
#
#    def hello(self):
#        name = self.nameInput.get() or 'world'
#        messagebox.showinfo('Message', ' %s 是hxj的儿子' % name)
#
#app = Application()
## 设置窗口标题:
#app.master.title('Hello World')
## 主消息循环:
#app.mainloop()



